package com.zyf.chapter02.behavior.iterator.snapshot;

import java.util.NoSuchElementException;

/**
 * 迭代器 <br />
 * 优点：基于接口而非实现编程，使用组合而不是继承
 * @author yifeng
 */
public class ArrayIterator<E> implements Iterator<E> {
    private int cursor;
    private ArrayList<E> arrayList;

    public ArrayIterator(ArrayList<E> arrayList) {
        this.arrayList = arrayList;
        this.cursor = 0;
    }

    @Override
    public boolean hasNext() {
        // cursor 在指向最后一个元素的时候，hasNext == arrayList.size - 1
        return cursor != arrayList.size();
    }

    @Override
    public void next() {
        cursor++;
    }

    @Override
    public E currentItem() {
        if (cursor >= arrayList.size()) {
            throw new NoSuchElementException();
        }
        return arrayList.get(cursor);
    }

    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("yf");
        names.add("zyf");
        names.add("f");
        Iterator<String> iterator = new ArrayIterator<>(names);
        while (iterator.hasNext()) {
            System.out.println(iterator.currentItem());
            iterator.next();
        }
    }
}
